package com.example.srpingredissample;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@RestController
@RequestMapping
public class CarController {
    Logger log = LoggerFactory.getLogger(CarController.class);

    @Autowired
    CacheService cacheService;

    @Autowired
    CarRepository repository;
    @RequestMapping(value = {"addCar1"}, method = {RequestMethod.POST})
    public ResponseResult addCar1(@RequestBody Car car) {
        repository.save(car);
        return new ResponseResult("添加成功");
    }

    @RequestMapping(value = {"getCar"},method = {RequestMethod.GET})
    public List<Car> getCar(){
        List<Car> cars = cacheService.getList("key", Car.class);
        if (cars!= null && !cars.isEmpty()){
            log.info("redis中获取数据，返回给客户端");
            return cars;
        }
        List<Car> datas = repository.findAll();
        cacheService.add("key",datas,30, TimeUnit.SECONDS);
        log.info("数据库中获取到数据，入redis");
        return datas;
    }
}
